import zlib from 'zlib'
import {
  getCompareDataList,
  getStation,
  getLonAnalysis,
  getAZAnalysis,
  getAllBoundary
} from '@/apis/gis'

/**
 *  清除 地图痕迹
 *  value:0清除所有 1清除左右栅格 2清除所有的小区 3清除大栅格
 *  4清除小区4g 5清除小区5g 6清除营业厅 7清除车站 8清除左侧栅格
 *  9清除右侧栅格
 */
export function clearMap(value, gisObj, that = null) {
  const obj = {
    data: '',
    id: new Date().getTime(),
    type: 'cmcc'
  }
  if (gisObj) {
    switch (value) {
      case 0:
        gisObj.clearArea() // 清除 绘制多区域(点击)
        gisObj.setGrids(obj)
        gisObj.setContrastGrids(obj)
        gisObj.hideHeatMap()
        gisObj.hideCell(1)
        gisObj.hideCell(2)
        gisObj.closeBigGrid()
        gisObj.closeContrast()
        gisObj.setLegendType(0)
        that && that.businessHallLayer && that.businessHallLayer.hide()
        that && that.stationLayer && that.stationLayer.hide()
        gisObj.clearAreaGrid() //清除 多选区域 (无点击)
        break
      case 1:
        gisObj.setGrids(obj)
        gisObj.setContrastGrids(obj)
        gisObj.hideHeatMap()
        gisObj.leftGridData = null
        break
      case 2:
        gisObj.hideCell(1)
        gisObj.hideCell(2)
        break
      case 3:
        gisObj.closeBigGrid()
        break
      case 4:
        gisObj.hideCell(1)
        break
      case 5:
        gisObj.hideCell(2)
        break
      case 6:
        that && that.businessHallLayer && that.businessHallLayer.hide()
        break
      case 7:
        that && that.stationLayer && that.stationLayer.hide()
        break
      case 8:
        gisObj.hideLeftHeatMap()
        gisObj.setGrids(obj)

        break
      case 9:
        gisObj.hideRightHeatMap()
        gisObj.setContrastGrids(obj)

        break
    }
  }
}

/**
 *  修改平面图/卫星图
 *  id: 1平面 2卫星
 */
export function changeMap(id, gisObj) {
  id == 2 ? gisObj.showSatelliteMap() : gisObj.showStreetMap()
}

/**
 * 点击竞对 value:true/false
 */
export function compareFn(compare, gisObj) {
  switch (compare) {
    case true:
      if (gisObj) {
        gisObj.showContrast()
      }
      break
    case false:
      if (gisObj) {
        gisObj.closeContrast()
      }
      clearMap(9, gisObj)
      break
  }
}

/**
 * 图例
 */
export function setLegend(network, gisObj) {
  if (network) {
    const type = Number(network.split('+')[0])
    gisObj.setLegendType(type)
  } else {
    gisObj.setLegendType(0)
  }
}

/**
 * 修改图列类型
 */
export function setGridIndicatorType(network, gisObj) {
  if (network) {
    const type = Number(network.split('+')[0])
    gisObj.setGridIndicatorType(type)
  } else {
    gisObj.setGridIndicatorType(0)
  }
}

/**
 * 判断是否需要使用缓存还是新数据
 * formData 整合的form对象 包含 cityId, mnc, ptMonth, network
 * boundaryList： 保存缓存的数组 超过
 * status: 状态值 0左右，1左 2右
 * gisObj
 * boundary 当前筛选区域
 * callback 获取接口的方法回调
 * ifCommunity 是否是小区
 */
let globLFormData;
let globLStatus;
let globaBoundary;
export function getGridBoundary(
  formData,
  boundaryList,
  status,
  gisObj,
  boundary,
  callback,
  ifCommunity = false,
  pageNum='0'
) {
  globLFormData = formData;//提升到全局
  globLStatus = status;
  globaBoundary = boundary;
  let { cityId, zoneId, mnc, ptMonth, network, roleType } = formData
  // 暂时不知道干嘛的
  if (network != null) {
    const networkStr = network.split('+')[0]
    if (networkStr != 3 && networkStr != 5) {
      setLegend(network, gisObj)
      // if (networkStr == 6 || networkStr == 7) {
      setGridIndicatorType(network, gisObj)
      // }
    }
  } else {
    setLegend(null, gisObj)
    // setGridIndicatorType(null, gisObj)
  }
  // 首先清空下 图层
  if (network && ifCommunity) {
    let a = network.split('+')[1] == 4 ? 1 : 2
    delGisCommunity(a, gisObj)
  } else if (!ifCommunity) {
    // // 绘制边界
    // if( boundary ) setBoundary( boundary, gisObj )
    // 清除 热力图 网格图层
    delGisData(status, gisObj)
  }

  if (!network) {
    return
  }

  // 判断是否存在缓存,并且缓存时间是否超时 缓存时限1小时
  let maxTime = new Date().getTime() - 60 * 60 * 1000
  let item = boundaryList.filter(v => {
    if (v.mnc == mnc && v.ptMonth == ptMonth && v.network == network) {
      return v
    }
  })
  if (item && item.length > 0 && item[0].id > maxTime) {
    // 未调用接口 不做二层判断
    if (ifCommunity) {
      addGisCommunity(item[0]['data'], network, gisObj)
    } else {
      let ifDefault = false
      if (zoneId == cityId && roleType == 1) {
        ifDefault = true
      }
      addGisData(
        item[0]['data'],
        { network, status },
        ifDefault,
        gisObj,
        boundary
      )
    }
  } else if (mnc != null && ptMonth != null && network != null) {
    // 调用 接口获取

    getBoundary(formData, status, callback, boundary, gisObj,pageNum)
  }
}

/**
 * 获取栅格和小区和区域图层 接口
 * formData 整合的form对象 包含 cityId, mnc, ptMonth, network
 * * network: 样例'1+4' ( type: 1, cellType: 4);
 * status: 状态值 0左右，1左 2右
 * callback 方法回调
 */
 let data = ""
export function getBoundary(formData, status, callback, boundary, gisObj,pageNum) {
  let {
    cityId,
    mnc,
    ptMonth,
    network,
    type,
    day,
    townId,
    zoneId,
    routeAreaType,
    ptDay
  } = formData
  const id = new Date().getTime()
  type = type ? type : network.split('+')[0]
  let cellType = network.split('+')[1]
  let oReq = new XMLHttpRequest()
  cellType ? cellType : ''
  day ? day : ''
  const path =
    routeAreaType == 5 &&
    day &&
    townId &&
    townId != '全部' &&
    zoneId &&
    zoneId != '全部'
      ? '&type=' +
        type +
        '&day=' +
        day +
        '&townId=' +
        townId +
        '&zoneId=' +
        zoneId
      : '&type=' + type
      
  let dayTime = ptDay ? '&ptDay=' + ptDay : ''
  oReq.open(
    'GET',
    process.env.VUE_APP_API_URL +
      '/caict/gisAnalysis/getGisLayerByStream?cityId=' +
      cityId +
      '&mnc=' +
      mnc +
      '&ptMonth=' +
      ptMonth +
      dayTime +
      '&cellType=' +
      cellType +
      '&id=' +
      id +
      '&pageNum='+
      pageNum +
      path,
    true
  )
  oReq.responseType = 'arraybuffer'
  oReq.setRequestHeader(
    'Authorization',
    'Bearer ' + localStorage.getItem('Authorization')
  )
  oReq.onloadend = function (_event) {
    const ab = oReq.response
    const buff = Buffer.from(ab)
   
    try {
      data += zlib.gunzipSync(buff).toString('utf-8')
    } catch (error) {
      console.error(error)
      return
    }

    console.log('调用后台成功')
    let gridData = {
      id: id,
      type: mnc == '0' ? 'cmcc' : mnc == '1' ? 'cucc' : 'cmcc',
      data: data
    }
    console.log(data)
    callback(formData, gridData, status, boundary)
  }
  oReq.send()
}

/**
 * 渲染 栅格
 * status 状态 0同时开启左侧和右侧栅格
 * 1 开启左侧栅格 2开启右侧栅格
 * type 1网络 3用户 4网络质量 5漫入用户
 */
export function addGisData(
  s,
  { network, status },
  ifDefault = false,
  gisObj,
  boundary
) {
  console.log('调用 gis方法')
  let type = network.split('+')[0]
  // 调用加载方法之前 先清理 旧数据
  delGisData(status, gisObj)
  // 除小区之外 筛选项的图层

  // 同名计时器未执行方法会被覆盖
  // *****************热力图重新绘制会有错误数据的bug 为GIS 自带bug 调用计时器可以看到 图层删除操作与bug无关， 重绘图层自己产生bug*********************************
  setTimeout(() => {
    // console.log(type, status, s, ifDefault, boundary)
    switch (status) {
      case 0:
        // 基本不可能0
        if (type == 3 || type == 5 || type == 16) {
          gisObj.setHeatMap(s)
          gisObj.setContrastHeatMap(s)
        } else {
          gisObj.setGrids(s)
          gisObj.setContrastGrids(s)
        }

        break
      case 1:
        if (type == 3 || type == 5 || type == 7 || type == 16) {
          if (ifDefault) {
            gisObj.setHeatMap(s)
            return
          }
          if (boundary) {
            gisObj.setHeatMapAndBoundary(s.data, boundary.boundary)
          } else {
            gisObj.setHeatMap(s)
          }
        } else {
          if (ifDefault) {
            gisObj.setGrids(s)
            return
          }
          if (boundary) {
            gisObj.setGridsMap(s.data, boundary.boundary)
          } else {
            gisObj.setGrids(s)
          }
        }
        break
      case 2:
        if (type == 3 || type == 5) {
          if (ifDefault) {
            gisObj.setContrastHeatMap(s)
            return
          }
          if (boundary) {
            gisObj.setContrastHeatMapAndBoundary(s.data, boundary.boundary)
          } else {
            gisObj.setContrastHeatMap(s)
          }
        } else {
          if (ifDefault) {
            gisObj.setContrastGrids(s)
            return
          }
          if (boundary) {
            gisObj.setContrastGridsMap(s.data, boundary.boundary)
          } else {
            gisObj.setContrastGrids(s)
          }
        }
        break
    }
  }, 50)
}
/**
 * 渲染 小区
 * status 状态 0同时开启左侧和右侧栅格
 * 1 开启左侧栅格 2开启右侧栅格
 * type 2小区
 */
export function addGisCommunity(s, network, gisObj) {
  // 小区的 图层
  let cellType = network.split('+')[1]
  const a = cellType == 4 ? 1 : 2
  console.log(a)
  if (!s) return
  delGisCommunity(a, gisObj)
  gisObj.setCells(a, s.data)
  gisObj.showCell(a)
}
/**
 * 清空 栅格
 * status 状态 0同时关闭左侧和右侧栅格
 * 1 关闭左侧栅格 2关闭右侧栅格
 */
export function delGisData(status, gisObj) {
  // 清空 旧图层
  if (status == 1) {
    clearMap(8, gisObj)
  } else if (status == 2) {
    clearMap(9, gisObj)
  } else {
    clearMap(8, gisObj)
    clearMap(9, gisObj)
    clearMap(16, gisObj)
  }
}

/**
 * 清空 小区
 * status 状态 0同时关闭4g和右5g
 * 1 关闭4G 2关闭5g
 */
export function delGisCommunity(status, gisObj) {
  // 清空 旧图层
  if (status == 1) {
    clearMap(4, gisObj)
  } else if (status == 2) {
    clearMap(5, gisObj)
  } else {
    clearMap(4, gisObj)
    clearMap(5, gisObj)
  }
}

/**
 * 经纬度分析 接口 方位角分析 接口
 * perspective: 1经纬度分析 2方位角分析
 */
export async function getLonAndAz(formData, gisObj, callback) {
  const {
    cityId,
    mnc,
    ptMonth,
    perspective,
    stateType,
    longitudeType,
    azimuthType,
    sortType
  } = formData
  let obj = {
    cityId,
    zoneId: cityId,
    type: perspective == 1 ? longitudeType : azimuthType, //经纬度距离偏差类型
    cellType: stateType == 1 ? 0 : stateType == 2 ? 4 : 5,
    mnc,
    ptMonth
  }
  if (perspective == 1) {
    const { data } = await getLonAnalysis({ ...obj, sortType })
    gisObj.setOffsetSites(data)
    callback(data)
  } else {
    const { data } = await getAZAnalysis(obj)
    gisObj.setOffsetCells(data)
    callback(data)
  }
}

/**
 * 经纬度、方位角 定位到地图的接口
 * perspective: 1经纬度分析 2方位角分析
 */
export function getLocateCell(perspective, cId, gisObj) {
  switch (perspective) {
    case 1: //经纬度
      gisObj.locateSite(cId)
      break
    case 2: //方位角
      gisObj.locateCell(cId)
      break
  }
}

/**
 * 绘制多边界 无点击效果
 */
export async function getAllBoundaryNoClick(
  cityId,
  type,
  gisObj,
  routeAreaType
) {
  gisObj.clearAreaGrid()
  if (type == null) {
    return
  } else {
    let obj = {
      cityId,
      type
    }
    const { data } = await getAllBoundary(obj)
    if (routeAreaType == 5) {
      if (data) {
        //  有点击效果
        gisObj.setArea(data)
        gisObj.unSelectArea()
        gisObj.clearBoundary()
      } else {
        gisObj.clearArea()
      }
    } else {
      // 无点击效果
      if (data) gisObj.setAreaGrid(data)
    }
  }
}

/**
 * 车站/营业厅 接口
 *
 * v 2:车站 1:营业厅
 * type: hide / show
 */
export async function getStations(custom, type, that = null) {
  let v = custom == 11 ? 1 : 2
  if (that && that.state.gisPage) {
    let gis = that.state.gisPage
    if (type === 'hide') {
      if (v == 1) {
        gis.businessHallLayer && gis.businessHallLayer.hide()
      } else {
        gis.stationLayer && gis.stationLayer.hide()
      }
    } else {
      const { data = '' } = await getStation({ type: v })
      if (data && data.length > 0) {
        if (v == 2) {
          // 车站
          gis.stationLayer.setData(data)
          gis.stationLayer.show()
        } else {
          // 营业厅
          gis.businessHallLayer.setData(data)
          gis.businessHallLayer.show()
        }
      }
    }
  }
}

/**
 * 5*5栅格 接口 渲染 大栅格
 */
export async function bigGridContrast(formData, gisObj, callback) {
  const { ptMonth, cityId, network, offset, offsetSort } = formData

  const obj = {
    ptMonth,
    cityId,
    cellType: network != null ? network.split('+')[1] : '4',
    compareType: offset,
    sortType: offsetSort.sortType,
    sortStr: offsetSort.sortStr
  }
  if (offset != null) {
    const { data = [] } = await getCompareDataList(obj)
    if (data && data.length > 0) {
      const datas = data.map(v => {
        return {
          grid_id: v.gridId,
          cmcc: v.mobileCoverRate.toFixed(2),
          ctcc: v.telecomCoverRate.toFixed(2),
          cucc: v.unicomCoverRate.toFixed(2)
        }
      })
      callback(data)
      gisObj.setBigGrid(datas)
    } else {
      clearMap(3, gisObj)
    }
  } else {
    gisObj.setBigGrid([])
  }
}
/**
 * 5*5栅格 id跳转
 */
export function zoomToBigGrid(cId, gisObj) {
  if (gisObj) gisObj.zoomToBigGrid(cId)
}

/**
 * 绘制单独区域 跳转
 */
export function setBoundary(data, gisObj) {
  if (data && gisObj) gisObj.setBoundary(data)
}

/**
 * 绘制单独区域 跳转 清除
 */
export function clearBoundary(gisObj) {
  if (gisObj) gisObj.clearBoundary()
}

/**
 * 绘制多边界 有点击效果
 */
export async function getAllBoundaryHaveClick(formData, gisObj) {
  let {
    cityId,
    zoneId,
    townId,
    networkGridId,
    microGridId,
    areaType,
    ptMonth
  } = formData
  if (areaType == null) {
    gisObj.clearArea()
  } else {
    let obj = {}
    if (zoneId) {
      let townId2 = townId == '全部' ? null : townId
      obj = {
        cityId,
        zoneId,
        townId: townId2,
        areaType,
        type: 3,
        ptMonth
      }
    } else {
      let microGridId2 = microGridId == '全部' ? null : microGridId
      obj = {
        cityId,
        networkGridId,
        microGridId: microGridId2,
        areaType,
        type: 3,
        ptMonth
      }
    }

    const { data } = await getAllBoundary(obj)
    if (data) {
      gisObj.setArea(data)
    } else {
      gisObj.clearArea()
    }
  }
}

/**
 * 绘制多边界 单独区域 跳转
 */
export function locateArea(id, gisObj) {
  if (!id) {
    if (gisObj) gisObj.unSelectArea()
  } else {
    if (gisObj) gisObj.locateArea(id)
  }
}
